/**
 * 智慧小区管理系统 - 应用状态管理 Store
 * @author Wu.Liang
 * @date 2024-01-01
 * @updated 2024-12-21 - 完善应用状态管理，增强配置和主题管理
 * @updated 2025-01-30 - 添加应用就绪状态管理，解决页面重复展示问题
 */
import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { useUserStore } from './user'

interface AppConfig {
    // 主题设置
    theme: 'light' | 'dark' | 'auto'
    primaryColor: string
    fontSize: 'small' | 'medium' | 'large'

    // 语言设置
    language: string

    // 布局设置
    sidebarCollapsed: boolean
    sidebarWidth: number
    headerHeight: number

    // 功能设置
    showBreadcrumb: boolean
    showTags: boolean
    showFooter: boolean

    // 性能设置
    enableCache: boolean
    enableAnimation: boolean
    enableSound: boolean
}

interface SystemInfo {
    version: string
    buildTime: string
    environment: string
    userAgent: string
    screenSize: {
        width: number
        height: number
    }
    viewport: {
        width: number
        height: number
    }
}

export const useAppStore = defineStore('app', () => {
    // 状态数据
    const config = ref<AppConfig>({
        theme: 'light',
        primaryColor: '#1890ff',
        fontSize: 'medium',
        language: 'zh-CN',
        sidebarCollapsed: false,
        sidebarWidth: 200,
        headerHeight: 60,
        showBreadcrumb: true,
        showTags: true,
        showFooter: true,
        enableCache: true,
        enableAnimation: true,
        enableSound: true
    })

    const systemInfo = ref<SystemInfo>({
        version: '1.0.0',
        buildTime: '',
        environment: 'development',
        userAgent: navigator.userAgent,
        screenSize: {
            width: window.screen.width,
            height: window.screen.height
        },
        viewport: {
            width: window.innerWidth,
            height: window.innerHeight
        }
    })

    const loading = ref(false)
    const loadingText = ref('')
    const error = ref<string | null>(null)
    const isReady = ref(false) // 应用就绪状态 - 新增
    const isMobile = ref(false)
    const isTablet = ref(false)
    const isDesktop = ref(true)

    // 计算属性
    const isDarkTheme = computed(() => {
        if (config.value.theme === 'auto') {
            return window.matchMedia('(prefers-color-scheme: dark)').matches
        }
        return config.value.theme === 'dark'
    })

    const isLightTheme = computed(() => {
        if (config.value.theme === 'auto') {
            return !window.matchMedia('(prefers-color-scheme: dark)').matches
        }
        return config.value.theme === 'light'
    })

    const isAutoTheme = computed(() => {
        return config.value.theme === 'auto'
    })

    // 应用就绪状态管理方法 - 新增
    const setReady = (ready: boolean) => {
        isReady.value = ready
        console.log('应用就绪状态更新:', ready)
    }

    const waitForReady = (): Promise<void> => {
        return new Promise((resolve) => {
            if (isReady.value) {
                resolve()
            } else {
                const checkReady = () => {
                    if (isReady.value) {
                        resolve()
                    } else {
                        setTimeout(checkReady, 50)
                    }
                }
                checkReady()
            }
        })
    }

    const sidebarWidth = computed(() => {
        return config.value.sidebarCollapsed ? 64 : config.value.sidebarWidth
    })

    const mainContentWidth = computed(() => {
        return `calc(100vw - ${sidebarWidth.value}px)`
    })

    const fontSizeClass = computed(() => {
        return `font-size-${config.value.fontSize}`
    })

    const themeClass = computed(() => {
        return `theme-${config.value.theme}`
    })

    // 初始化应用
    const initApp = async () => {
        try {
            loading.value = true
            loadingText.value = '初始化中...'

            // 检测设备类型
            detectDeviceType()

            // 监听窗口大小变化
            window.addEventListener('resize', handleResize)

            // 监听系统主题变化
            if (config.value.theme === 'auto') {
                window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', handleThemeChange)
            }

            // 加载配置
            await loadConfig()

            // 应用主题
            await applyTheme()

            // 应用语言
            await applyLanguage()

            isReady.value = true
            loading.value = false
        } catch (error) {
            console.error('应用初始化失败:', error)
            setError('应用初始化失败')
            loading.value = false
        }
    }

    // 检测设备类型
    const detectDeviceType = () => {
        const width = window.innerWidth
        isMobile.value = width < 768
        isTablet.value = width >= 768 && width < 1024
        isDesktop.value = width >= 1024

        // 移动端自动折叠侧边栏
        if (isMobile.value && !config.value.sidebarCollapsed) {
            config.value.sidebarCollapsed = true
        }
    }

    // 处理窗口大小变化
    const handleResize = () => {
        detectDeviceType()
        updateViewportInfo()
    }

    // 处理主题变化
    const handleThemeChange = () => {
        if (config.value.theme === 'auto') {
            applyTheme()
        }
    }

    // 更新视口信息
    const updateViewportInfo = () => {
        systemInfo.value.viewport = {
            width: window.innerWidth,
            height: window.innerHeight
        }
    }

    // 加载配置
    const loadConfig = async () => {
        try {
            const stored = localStorage.getItem('appConfig')
            if (stored) {
                const storedConfig = JSON.parse(stored)
                config.value = { ...config.value, ...storedConfig }
            }
        } catch (error) {
            console.error('加载配置失败:', error)
        }
    }

    // 保存配置
    const saveConfig = () => {
        try {
            localStorage.setItem('appConfig', JSON.stringify(config.value))
        } catch (error) {
            console.error('保存配置失败:', error)
        }
    }

    // 更新配置
    const updateConfig = async (newConfig: Partial<AppConfig>) => {
        config.value = { ...config.value, ...newConfig }
        saveConfig()

        // 如果更新了主题，应用主题
        if (newConfig.theme !== undefined) {
            await applyTheme()
        }

        // 如果更新了语言，应用语言
        if (newConfig.language !== undefined) {
            await applyLanguage()
        }
    }

    // 应用主题
    const applyTheme = async () => {
        try {
            const root = document.documentElement
            const isDark = isDarkTheme.value

            // 设置CSS变量
            if (isDark) {
                root.style.setProperty('--primary-color', '#1890ff')
                root.style.setProperty('--background-color', '#1f1f1f')
                root.style.setProperty('--text-color', '#ffffff')
                root.style.setProperty('--border-color', '#333333')
                root.style.setProperty('--card-background', '#2a2a2a')
                root.style.setProperty('--hover-color', '#404040')
            } else {
                root.style.setProperty('--primary-color', config.value.primaryColor)
                root.style.setProperty('--background-color', '#ffffff')
                root.style.setProperty('--text-color', '#000000')
                root.style.setProperty('--border-color', '#e8e8e8')
                root.style.setProperty('--card-background', '#ffffff')
                root.style.setProperty('--hover-color', '#f5f5f5')
            }

            // 设置主题类名
            root.className = root.className.replace(/theme-\w+/g, '')
            root.classList.add(`theme-${config.value.theme}`)

            // 更新HTML的data-theme属性
            document.documentElement.setAttribute('data-theme', config.value.theme)
        } catch (error) {
            console.error('应用主题失败:', error)
        }
    }

    // 应用语言
    const applyLanguage = async () => {
        try {
            // 这里可以集成i18n国际化
            document.documentElement.setAttribute('lang', config.value.language)
        } catch (error) {
            console.error('应用语言失败:', error)
        }
    }

    // 切换侧边栏
    const toggleSidebar = () => {
        config.value.sidebarCollapsed = !config.value.sidebarCollapsed
        saveConfig()
    }

    // 设置侧边栏状态
    const setSidebarCollapsed = (collapsed: boolean) => {
        config.value.sidebarCollapsed = collapsed
        saveConfig()
    }

    // 显示加载
    const showLoading = (text = '加载中...') => {
        loading.value = true
        loadingText.value = text
    }

    // 隐藏加载
    const hideLoading = () => {
        loading.value = false
        loadingText.value = ''
    }

    // 设置错误
    const setError = (message: string) => {
        error.value = message
    }

    // 清除错误
    const clearError = () => {
        error.value = null
    }

    // 重置配置
    const resetConfig = () => {
        const defaultConfig: AppConfig = {
            theme: 'light',
            primaryColor: '#1890ff',
            fontSize: 'medium',
            language: 'zh-CN',
            sidebarCollapsed: false,
            sidebarWidth: 200,
            headerHeight: 60,
            showBreadcrumb: true,
            showTags: true,
            showFooter: true,
            enableCache: true,
            enableAnimation: true,
            enableSound: true
        }
        config.value = defaultConfig
        saveConfig()
        applyTheme()
        applyLanguage()
    }

    // 获取系统信息
    const getSystemInfo = () => {
        updateViewportInfo()
        return systemInfo.value
    }

    // 监听配置变化，自动保存
    watch(config, () => {
        saveConfig()
    }, { deep: true })

    // 监听用户登录状态变化
    watch(() => useUserStore().isLogged, (isLogged) => {
        if (!isLogged) {
            // 用户登出时清除错误状态
            clearError()
        }
    })

    return {
        // 状态
        config,
        systemInfo,
        loading,
        loadingText,
        error,
        isReady,
        isMobile,
        isTablet,
        isDesktop,

        // 计算属性
        isDarkTheme,
        isLightTheme,
        isAutoTheme,
        sidebarWidth,
        mainContentWidth,
        fontSizeClass,
        themeClass,

        // 方法
        initApp,
        updateConfig,
        toggleSidebar,
        setSidebarCollapsed,
        showLoading,
        hideLoading,
        setError,
        clearError,
        resetConfig,
        getSystemInfo,
        applyTheme,
        applyLanguage,
        setReady,
        waitForReady
    }
})
